package secondriver.ccs.parallel;

import javax.imageio.ImageIO;
import javax.imageio.stream.FileImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.RecursiveTask;

/**
 * Author : secondriver
 */
public final class CreatorFileTaskUnit extends RecursiveTask<String> implements CcsCommon {

    /**
     * 生成的图片格式及其后缀
     */
    public static final String IMAGE_TYPE = ".png";

    /**
     * 默认生成的图片宽高
     */
    public static final int DEFAULT_IMAGE_W_H = 480;

    private ComputeResult computeResult;

    private int imageWithHeight;

    public CreatorFileTaskUnit(ComputeResult computeResult) {
        this(computeResult, DEFAULT_IMAGE_W_H);
    }

    /**
     * 计算结果生成图片（用户目录）
     *
     * @param computeResult   计算结果
     * @param imageWithHeight 图片宽高，默认是480
     */
    public CreatorFileTaskUnit(ComputeResult computeResult, int imageWithHeight) {
        this.computeResult = computeResult;
        this.imageWithHeight = imageWithHeight;
    }

    @Override
    protected String compute() {

        int edge = computeResult.getEdge();
        int sid = computeResult.getSid();
        byte[] operator = computeResult.getOperator();

        System.out.println("***CreatorFileTaskUnit-Compute: edge=" + edge + ", sid=" + sid + "...");

        String fileName = System.getProperty("user.home") + "/" + edge + "_" + sid + IMAGE_TYPE;

        try (FileImageOutputStream fos = new FileImageOutputStream(new File(fileName))) {

            int cellLen = imageWithHeight / edge;

            //修复黑边
            int whFix = cellLen * edge;

            BufferedImage bufferedImage = new BufferedImage(whFix, whFix, BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = bufferedImage.createGraphics();
            g2d.getDeviceConfiguration().createCompatibleImage(whFix, whFix, Transparency.TRANSLUCENT);
            g2d.dispose();
            g2d = bufferedImage.createGraphics();
            g2d.setBackground(Color.BLACK);


            int size = operator.length;
            for (int i = 0; i < edge; i++) {
                for (int j = 0; j < edge; j++) {
                    Rectangle rect = new Rectangle(cellLen * j, cellLen * i, cellLen, cellLen);
                    int index = i * edge + j;
                    if (index < size && operator[index] == ONE) {
                        g2d.setColor(Color.RED);
                        g2d.fill(rect);
                        g2d.setColor(Color.WHITE);
                        g2d.draw(rect);
                    } else {
                        g2d.setColor(Color.WHITE);
                        g2d.draw(rect);
                    }
                }
            }
            g2d.dispose();
            ImageIO.write(bufferedImage, IMAGE_TYPE.substring(1), fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fileName;
    }
}